<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">面包管理</h1>
      <n-button type="primary" @click="handleAdd">
        <template #icon>
          <n-icon><AddOutline /></n-icon>
        </template>
        新增面包
      </n-button>
    </div>
    
    <!-- 搜索栏 -->
    <n-card style="margin-bottom: 16px;">
      <n-space>
        <n-input 
          v-model:value="searchParams.keyword" 
          placeholder="搜索面包名称" 
          clearable 
          style="width: 200px;"
        />
        <n-select 
          v-model:value="searchParams.category" 
          placeholder="分类" 
          clearable 
          :options="categoryOptions"
          style="width: 150px;"
        />
        <n-select 
          v-model:value="searchParams.status" 
          placeholder="状态" 
          clearable 
          :options="statusOptions"
          style="width: 150px;"
        />
        <n-button type="primary" @click="handleSearch">搜索</n-button>
        <n-button @click="handleReset">重置</n-button>
      </n-space>
    </n-card>
    
    <!-- 表格 -->
    <div class="table-wrapper">
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :bordered="false"
        @update:page="handlePageChange"
      />
    </div>
    
    <!-- 新增/编辑对话框 -->
    <n-modal v-model:show="showModal" preset="dialog" :title="modalTitle" style="width: 600px;">
      <n-form ref="formRef" :model="formData" :rules="rules" label-placement="left" label-width="100">
        <n-form-item label="面包名称" path="name">
          <n-input v-model:value="formData.name" placeholder="请输入面包名称" />
        </n-form-item>
        <n-form-item label="分类" path="category">
          <n-select v-model:value="formData.category" :options="categoryOptions" placeholder="请选择分类" />
        </n-form-item>
        <n-form-item label="单价" path="price">
          <n-input-number v-model:value="formData.price" :min="0" :precision="2" placeholder="请输入单价">
            <template #suffix>元</template>
          </n-input-number>
        </n-form-item>
        <n-form-item label="规格" path="specification">
          <n-input v-model:value="formData.specification" placeholder="如：500g/条" />
        </n-form-item>
        <n-form-item label="描述" path="description">
          <n-input 
            v-model:value="formData.description" 
            type="textarea" 
            placeholder="请输入描述"
            :rows="3"
          />
        </n-form-item>
        <n-form-item v-if="!formData.id" label="初始库存" path="stock">
          <n-input-number v-model:value="formData.stock" :min="0" placeholder="请输入初始库存">
            <template #suffix>个</template>
          </n-input-number>
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="formData.status">
            <n-radio :value="1">在售</n-radio>
            <n-radio :value="0">已下架</n-radio>
          </n-radio-group>
        </n-form-item>
      </n-form>
      
      <template #action>
        <n-space>
          <n-button @click="showModal = false">取消</n-button>
          <n-button type="primary" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, h, onMounted, reactive } from 'vue'
import { getBreadPage, addBread, updateBread, deleteBread } from '@/api/bread'
import { 
  NButton, NIcon, NCard, NSpace, NInput, NSelect, NDataTable, NTag, NModal,
  NForm, NFormItem, NInputNumber, NRadioGroup, NRadio, useMessage, useDialog
} from 'naive-ui'
import { AddOutline, CreateOutline, TrashOutline } from '@vicons/ionicons5'

const message = useMessage()
const dialog = useDialog()

const loading = ref(false)
const tableData = ref([])
const showModal = ref(false)
const modalTitle = ref('新增面包')
const formRef = ref(null)

const searchParams = reactive({
  keyword: '',
  category: null,
  status: null
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})

const categoryOptions = [
  { label: '甜面包', value: '甜面包' },
  { label: '咸面包', value: '咸面包' },
  { label: '吐司', value: '吐司' }
]

const statusOptions = [
  { label: '在售', value: 1 },
  { label: '已下架', value: 0 }
]

const formData = ref({
  id: null,
  name: '',
  category: null,
  price: null,
  specification: '',
  description: '',
  stock: 0,
  status: 1
})

const rules = {
  name: { required: true, message: '请输入面包名称', trigger: 'blur' },
  category: { required: true, message: '请选择分类', trigger: 'change' },
  price: { required: true, type: 'number', message: '请输入单价', trigger: 'blur' }
}

const columns = [
  { title: 'ID', key: 'id', width: 80 },
  { title: '名称', key: 'name' },
  { 
    title: '分类', 
    key: 'category',
    render: (row) => {
      const colorMap = { '甜面包': 'warning', '咸面包': 'info', '吐司': 'success' }
      return h(NTag, { type: colorMap[row.category] }, { default: () => row.category })
    }
  },
  { 
    title: '单价', 
    key: 'price',
    render: (row) => `¥${row.price}`
  },
  { title: '规格', key: 'specification' },
  { 
    title: '库存', 
    key: 'stock',
    render: (row) => {
      const type = row.stock > 20 ? 'success' : row.stock > 0 ? 'warning' : 'error'
      return h(NTag, { type }, { default: () => row.stock })
    }
  },
  { 
    title: '状态', 
    key: 'status',
    render: (row) => {
      return h(NTag, { type: row.status === 1 ? 'success' : 'default' }, { 
        default: () => row.status === 1 ? '在售' : '已下架' 
      })
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    render: (row) => {
      return h(NSpace, {}, {
        default: () => [
          h(NButton, {
            size: 'small',
            onClick: () => handleEdit(row)
          }, { 
            default: () => '编辑',
            icon: () => h(NIcon, {}, { default: () => h(CreateOutline) })
          }),
          h(NButton, {
            size: 'small',
            type: 'error',
            onClick: () => handleDelete(row)
          }, { 
            default: () => '下架',
            icon: () => h(NIcon, {}, { default: () => h(TrashOutline) })
          })
        ]
      })
    }
  }
]

async function loadData() {
  try {
    loading.value = true
    const res = await getBreadPage({
      page: pagination.page,
      size: pagination.pageSize,
      ...searchParams
    })
    tableData.value = res.data.records
    pagination.itemCount = res.data.total
  } catch (error) {
    message.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  pagination.page = 1
  loadData()
}

function handleReset() {
  searchParams.keyword = ''
  searchParams.category = null
  searchParams.status = null
  pagination.page = 1
  loadData()
}

function handlePageChange(page) {
  pagination.page = page
  loadData()
}

function handleAdd() {
  modalTitle.value = '新增面包'
  formData.value = {
    id: null,
    name: '',
    category: null,
    price: null,
    specification: '',
    description: '',
    stock: 0,
    status: 1
  }
  showModal.value = true
}

function handleEdit(row) {
  modalTitle.value = '编辑面包'
  formData.value = { ...row }
  showModal.value = true
}

function handleDelete(row) {
  dialog.warning({
    title: '确认下架',
    content: `确定要下架「${row.name}」吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await deleteBread(row.id)
        message.success('下架成功')
        loadData()
      } catch (error) {
        message.error(error.message || '下架失败')
      }
    }
  })
}

async function handleSubmit() {
  try {
    await formRef.value?.validate()
    
    if (formData.value.id) {
      await updateBread(formData.value)
      message.success('更新成功')
    } else {
      await addBread(formData.value)
      message.success('新增成功')
    }
    
    showModal.value = false
    loadData()
  } catch (error) {
    if (error.message) {
      message.error(error.message)
    }
  }
}

onMounted(() => {
  loadData()
})
</script>

